#include "fig_app.h"
#include "build.h"	
//#include "knb_vars.h"
#include "gen_game_state.h"
#include "fig_ui_levelselect.h"
#include "fig_ui_pausemenu.h"
#include "fig_ui_comic.h"
#include "fig_sounds.h"
#include "fig_vars.h"
#include "fig_constants.h"  

#include "fig_ui_language.h"
#include "fig_mainmenu.h"
//#include "fig_ui_removead.h"
//#include "fig_ui_generalinfo.h"

#ifdef _WINDOWS
#include "fig_tool_bone_producer.h"
#endif

#include "fig_gamecenter.h"
#ifdef _PLATFORM_IOS

#ifndef  PRO_VERSION
#include "inapppurchase/inapppurchasemanager.h"
#endif
#endif

#ifdef _PLATFORM_ANDROID
#include "SDL2/src/core/android/SDL_android.h"
#include "android/sleipner_android.h"
#endif


//#include "pvu_credits_state.h"
#include "resman/resman.h"
#include "lang/strman.h"
#include "script/file_list.h"

#include "num/rand.h"


#include "application/boot_loader.h"
#include "application/credit_state.h"


#include "console/console.h"
#include "font/font_manager.h"
#include "font/font.h"
#include "ui/ui_manager.h"
#include "ui/ui_skin.h"

#include "gameflow/game_flow_manager.h"
#include "gameflow/ui_state.h"
#include "gameflow/ui_popup.h"

//#include "bones/biped_instance.h"

#include "vfs/vfs.h"
#include "vfs/archive.h"

#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    
#include "util/timer.h"		    
#include <cassert>




using namespace gameflow;

static std::string	ForceLevel;
static void UpdateLoadCB(void* pData);


Font* FIGApp::m_pEnglishFont = NULL;
Font* FIGApp::m_pUnicodeFont = NULL;


FIGApp::FIGApp (	WindowHandler*	pHandler, 
                const			std::string& Config, 
                const			std::string& Log) :
													GameApp(	pHandler, 
															Config, 
															Log),
													m_pWorld(0),
													m_DebugLoadingCount(0)
													
{
    
}

FIGApp::~FIGApp()
{
	UTIL_SAFE_DELETE(m_pWorld);    
}

bool      FIGApp::Shutdown()
{            
#ifndef PRO_VERSION
	AdManager::Instance().ShutDown();
#endif


	//FIGGameCenter::Instance()->ShutDown();


    return GameApp::Shutdown();
}

void		FIGApp::LoadArchives()
{

#ifdef _PLATFORM_ANDROID
	AdManager::Instance().RequestBannerAd();
#endif
    
	_LOG(MSG_COMMENT, "LOADING ARCHIVE ------------------------------------------");
	GetHandler()->UpdateOS();    
#if  defined(_PLATFORM_IOS) || defined(_PLATFORM_ANDROID)
	vfs::Archive* pArc = vfs::VFS::Instance().AddArchive("ac.aac");
#else

//#ifdef  NDEBUG
	vfs::Archive* pArc = vfs::VFS::Instance().AddArchive("ac.aac");
//#endif

	// use this block for unpacking data from archive
	//pArc->Unpack("C:\\Users\\2dstar\\Desktop\\data2\\");

#endif
    

//#ifdef NDEBUG
		/*    
     // use this block to make an archive 	
     vfs::Archive* pOutput = vfs::Archive::CreateArchive();
     script::FileList FL;
	 
	 FL.Build("atlas/*.png");
	 FL.Build("atlas/*.lua");

	 FL.Build("backgrounds/*.jpg");
	 FL.Build("decals/*.lua");
	 FL.Build("effects/*.png");
     FL.Build("effects/*.p2d");
	 FL.Build("effects/*.lua");
     FL.Build("fonts/*.png");     
	 FL.Build("fonts/*.lua");     
	 FL.Build("fonts/*.ttf");     
     FL.Build("scripts/*.*");
     FL.Build("sounds/*.ogg");
	 FL.Build("sounds/*.lua");
	 FL.Build("sounds/*.mp3");	 
	 FL.Build("sounds/*.wav");
	 FL.Build("img/*.png");
     FL.Build("img/*.jpg");
	 FL.Build("img/*.lua");
	 FL.Build("ui/*.ui");
	 FL.Build("ui_img/*.png");
	 FL.Build("ui_img/*.jpg");
	 FL.Build("ui_img/*.lua");
	 FL.Build("localization/*.*");    	 
	 FL.Build("levels/*.lua"); 
	 FL.Build("infos/*.lua"); 
	 FL.Build("anim/*.sbp"); 
	 FL.Build("char/*.lua"); 

	 FL.Build("bone_img/*.png");
	 FL.Build("bone_img/*.lua");
	 FL.Build("level_img/*.png");
	 FL.Build("level_img/*.lua");
	 FL.Build("level_enemy/*.lua");
	 FL.Build("level_bg_main/*.*");
	 FL.Build("level_bg/*.lua");
	 FL.Build("scripts/*.lua");
	 FL.Build("transform/*.lua");
	 FL.Build("splash/*.jpg");

	 //custom
	 FL.Build("ui_img/loading_button_black.png"); 
	 FL.Build("ui_img/loading_button_green.png"); 	
	 FL.Build("effects/flash02.png"); 
	 FL.Build("effects/hit.png");
	 
	 
	 for( int i = 0; i < FL.GetFileC(); i++)
     {
		std::string File =	FL.GetFileName(i);
		pOutput->AddFile(File);
     }
     pOutput->SaveArchive("ac.aac");
	 */

//#endif

  
}


void		FIGApp::OnCreateSplash()
{ 	
	GetHandler()->UpdateOS();
#if defined(WIN32) || defined(_PLATFORM_ANDROID)

	BootLoader	Splash;
	Splash.AddPage("splash/splash.jpg", 
					1, 
					1, 
					2, 
					false,
					"",
					true
					);

	Splash.SetSpeedSkip(true);
	while (!Splash.IsDone())
	{
		Splash.Tick();
		Splash.Render();		
		if(g_pApp && g_pApp->GetHandler())
			g_pApp->GetHandler()->Tick(0);
		//GetHandler()->UpdateOS();
	}	
#endif

	
    
}

void		FIGApp::OnBindKeys()
{
	GetHandler()->UpdateOS();
	console::Console::Instance().SetBackground("ui_img/black_bg.png");
	console::Console::Instance().PrintLastCommand(false);
	console::Console::Instance().Do("ReloadGame()");		// force it to reload the game scripts
	console::Console::Instance().BindKey(KEY_ESCAPE, "QuitGame()");
	console::Console::Instance().BindKey(KEY_F2, "CaptureAutoScreenshot()");
	console::Console::Instance().BindKey(KEY_F3, "CaptureMiniScreenshot()");
    
  	
}

GameRMS*	FIGApp::CreateRMS()
{
	return new FIGVars();
}

void		FIGApp::OnInitFonts()
{
	GetHandler()->UpdateOS();
	// we have done with graphic initialization , time to set loadupdate func
	 ui::UIManager::Instance().SetLoadCB(UpdateLoadCB, this); 
	
#ifdef _PLATFORM_WIN32
	const float FONT_WIDTH = 16.0f;
	const float FONT_HEIGHT = 20.0f;
#else
	const float FONT_WIDTH = 30.0f;
	const float FONT_HEIGHT = 30.0f;
#endif


	const float Scale = ((float)GetGraphics()->GetScreenWidth() / FIGConstants::IPHONE4_WIDTH);
    
	FontManager::Instance().Init("",(int)(FONT_WIDTH * Scale), int(FONT_HEIGHT * Scale));
	Font* pFont = 
	//FontManager::Instance().InitFont("smallfont","Pegasus", 8,16);
	//FontManager::Instance().InitBitmapFont("smallfont", "fonts/smallfont.lua");
	//FontManager::Instance().InitBitmapFont("tinyfont", "fonts/tinyfont.lua");
	//FontManager::Instance().InitBitmapFont("storytext", "fonts/storytext.lua");
	//FontManager::Instance().InitBitmapFont("mediumfont", "fonts/mediumfont.lua");
	//FontManager::Instance().InitBitmapFont("bigfont", "fonts/bigbont.lua");
	//FontManager::Instance().InitBitmapFont("gamefont", "fonts/gamefont.lua");
    
//#ifndef PRO_VERSION
	FontManager::Instance().InitFont(	"SmallFont",
										"fonts/DroidSans.ttf",
										//"Droid Sans",
										(int)(FONT_WIDTH * Scale * 0.95f),
										int(FONT_HEIGHT * Scale));
//#else
	//FontManager::Instance().InitBitmapFont("smallfont", "fonts/smallfont.lua");
//#endif
    
	//pFont->SetBorder(true);

	m_pUnicodeFont = pFont;

#ifdef _PLATFORM_WIN32
	pFont = 
	FontManager::Instance().InitFont(	"BigFont",
										"BankGothic Md BT",
										//"BankGothic Md BT",
										(int)(FONT_WIDTH * Scale ),
										int(FONT_HEIGHT * Scale * 1.2f));
#else

	pFont =
	FontManager::Instance().InitFont(	"BigFont",
										"fonts/bgothm.ttf",
										//"BankGothic Md BT",
										(int)(FONT_WIDTH * Scale ),
										int(FONT_HEIGHT * Scale * 1.2f ));
#endif

	m_pEnglishFont = pFont;
	FontManager::Instance().SetDefaultFont(m_pUnicodeFont);

	

    //		console::Console::Instance().SetFont(pFont);
	_LOG(MSG_INIT, "Font manager initialized");
}

void		FIGApp::OnCreateStates()
{
#ifdef WIN32
	GetHandler()->UpdateOS();
#endif
	// register custom components
	//GENBGSmoke::Register();

	// register custom states
	LuaPlus::LuaState*	pScript = console::Console::Instance().GetScript();
	//audio::AudioManager::Register(pScript);
	GENGameState::Register(pScript);
	//GENVars::Register(pScript);
    //		GameSummary::Register(pScript);
    //		GENMetaState::Register(pScript);
    
    // load savegames
    
	
    
	m_CurrentRate = 0;
//#ifdef _PLATFORM_WIN32
//	m_TargetRate = 534;
//#else
	m_TargetRate = 50;
//#endif
    
    
    
#ifdef _WINDOWS
#ifndef  NDEBUG
    //FIGToolBoneProducer *pBoneProducer = new FIGToolBoneProducer();
    //UTIL_SAFE_DELETE(pBoneProducer);
#endif
#endif


#ifndef PRO_VERSION    
    // Loading Itune Store
    if(FIGVars::Instance()->GetInt(FIGVars::VAR_NAMES_IS_FULL_VERSION) == 0)
    {
        //InAppPurchaseManager::Instance().LoadStore(FIGConstants::PRO_UPGRADE,
        //                                         NULL
        //                                           );
		const std::string BANNER_AD_KEY = "";
		const std::string FULLSCREEN_AD_APPID = "5143f54d17ba47dd3e000017";
		const std::string FULLSCREEN_AD_KEY = "b67489460c871f9e051b9294eb1d93dfd19702da";
		AdManager::Instance().AdInit(BANNER_AD_KEY, FULLSCREEN_AD_APPID, FULLSCREEN_AD_KEY, this);

	}
#endif

    
	//GetHandler()->UpdateOS();
	
	
  
//#ifdef WIN32
//	ui::SpriteSet::Instance().SetDeferLoading(false);	// load immediately
//	ui::SpriteSet::Instance().SetClamp(1);	// load immediately		
//#else
	ui::SpriteSet::Instance().SetDeferLoading(true);	// find now, load later
	ui::SpriteSet::Instance().SetClamp(0);	// find now, load later
    res::ResMan::Instance().SetForceSkipInit(true);     // not to load into texture yet
//#endif
    
	
	ui::SpriteSet::Instance().LoadAtlas("atlas/atlas.lua");
	ui::SpriteSet::Instance().AddSet("img/sprites.lua");
	ui::SpriteSet::Instance().AddSet("bone_img/sprites.lua");
	ui::SpriteSet::Instance().AddSet("level_img/sprites.lua");
	ui::SpriteSet::Instance().AddSet("level_bg_main/sprites.lua");
	
	ui::SpriteSet::Instance().AddSet("effects/sprites.lua");
	ui::SpriteSet::Instance().AddSet("ui_img/sprites.lua");

	  
    
	//ui::SpriteSet::Instance().SetDeferLoading(false);	// load immediately
	//ui::SpriteSet::Instance().SetClamp(1);	// load immediately		
	
	//ui::SpriteSet::Instance().SetDeferLoading(true);	// find now, load later
	//ui::SpriteSet::Instance().SetClamp(0);	// find now, load later
	
    
	// loaded for the bgedit
	//ui::SpriteSet::Instance().AddSet("decals/sprites2.lua");
	//ui::UISkin::Instance().Load("ui/test.skin");
    
    
	lang::StrMan::Instance().LoadLangBin("localization/English.bin");
	 
//#ifdef WIN32
//#else
	ui::SpriteSet::Instance().SetDeferLoading(false);	// find immediately
	ui::SpriteSet::Instance().SetClamp(1);	// load immediately
    res::ResMan::Instance().SetForceSkipInit(false);     // load immediately
    

//#endif 
    
	//ui::UIManager::Instance().RefreshText();
#ifdef WIN32
	GetHandler()->UpdateOS();
#endif
	
	assert(m_pCamera && "No valid camera found");
	gameflow::GameFlowManager&	Game = gameflow::GameFlowManager::Instance();
	Game.SetCamera(m_pCamera);
    
	_LOG(MSG_COMMENT, "DEBUG Before SetupUI  1 ------------------------------------------");
	// load ios setting for tilt etc
	SetupUI();
	_LOG(MSG_COMMENT, "DEBUG Before SetupUI  2 ------------------------------------------");
	//ui::UIManager::Instance().RefreshText();

	Game.AddTransitionState("MainMenu", new FIGMainMenu(m_pCamera));
	Game.AddTransitionState("after_loading",  new gameflow::UIState(m_pCamera,"ui/after_loading.ui","",""));
	float AspectRation = (float)( (float)GetGraphics()->GetScreenHeight()  / (float)GetGraphics()->GetScreenWidth());
	
	std::string File;
	//if( AspectRation >= 1.49f && AspectRation <= 1.51f)
		
	if(AspectRation >= 1.65f)
		File =	"ui/5_in_game.ui";
	else if(AspectRation <= 1.34 )
		File =	"ui/ipad_in_game.ui";
	else
		File =	"ui/in_game.ui";


	

	Game.AddTransitionState("game", m_pWorld = new GENGameState(m_pCamera,File,"",""));
	Game.AddTransitionState("level_select", new FIGUILevelSelect(m_pCamera));
	Game.AddTransitionState("comic_menu", new FIGUIComic(m_pCamera));	
	
    /*
	deprecated
	UIState*	pMain = (UIState*)Game.GetStateByName("MainMenu");
	if (pMain)
	{
		pMain->SetMusic(FIGSounds::MUSIC_MENU);
		pMain->SetupTransition("START_GAME", "level_select");		
	}
	*/
    
	Game.TransitionToState("after_loading",0.5f);
	UIState*	pState = (UIState*)Game.GetStateByName("after_loading");
	if (pState)
	{
		pState->SetupTransition("Background", "MainMenu");
		pState->GetWidget("Background")->OnMouseRelease(pState->GetWidget("Background")->GetPosition(),(int)input::Mouse::BUTTON_LEFT);
	}
    

    
    // loading gamecenter
//#ifdef _PLATFORM_IOS
	//FIGGameCenter::Instance()->Init();
//#endif


	/*
	Language
	int test = FIGVars::Instance()->GetInt(FIGVars::VAR_NAMES_LOCALIZATION_SELECTED);
	if( test == 0)
	{
		gameflow::UIPopupManager::Instance().StartPopup("ui/language.ui");
		FIGUILanguage::Instance().GetPopup()->GetWidget("Resume")->SetIsVisible(false);
		FIGVars::Instance()->SetInt(FIGVars::VAR_NAMES_LOCALIZATION_SELECTED,1);
	}
	else
	{
		FIGUILanguage::Instance().GetPopup()->GetWidget("ok_button")->SetIsVisible(false);
	}
	*/


    
	//gameflow::GameFlowManager::Instance().GetTransition().OnStateTransitionClicked(ui::UIWidget::WIDGET_EVENT::WE_LMB_CLICK,NULL);
    
	/*
     if (ForceLevel.empty())
     {
     Game.TransitionToState("game");
     if (GENGameState* pState = GENGameState::GetGame())
     {
     pState->CachedLoad("test");
     }
     
     } else
     {
     Game.TransitionToState("game");
     if (GENGameState* pState = GENGameState::GetGame())
     {
     pState->CachedLoad(ForceLevel);
     }
     
     }
     */
    
    //		m_IsInitialized = true;
	m_CurrentRate = 0;	// done loading!
	_LOG(MSG_COMMENT ,"Loading Files Count is");
	_LOG(MSG_COMMENT ,m_DebugLoadingCount);
    

    // we are done with you.
	ui::UIManager::Instance().SetLoadCB(NULL,NULL);

//#ifdef WIN32
//#else
	res::ResMan::Instance().FlushTexturesExceptUI();
//#endif

#ifdef _PLATFORM_ANDROID
    Android_JNI_SendMessage(FUNC_MOGA_SETLISTENER, 0);
#endif

   	AUDIO().Init("sounds/soundbank.lua");
	AUDIO().SetSFXVolume((int)m_pRMS->GetSoundVolume());
	_LOG(MSG_INIT, "Audio manager Init");
	
    
   
    
}

#ifndef PRO_VERSION

void		FIGApp::OnAdFullScreenShow()
{
	audio::BassAudio::Instance().PauseAll();
#ifdef _PLATFORM_IOS
    GENGameState::GetGame()->Pause();
#endif
}

void        FIGApp::OnAdFullScreenDismissed()
{
	audio::BassAudio::Instance().RestartAll();
#ifdef _PLATFORM_IOS
    GENGameState::GetGame()->UnPause();
#endif
}

#endif

// UI Events

void	FIGApp::SetupUI()
{
	GetHandler()->UpdateOS();
	GameApp::SetupUI();
	//FIGUILanguage::Instance();
	//FIGUIRemoveAd::Instance();
	//FIGUIPauseMenu::Instance();

	gameflow::UIPopupManager::Instance().AddPopup("ui/connecting.ui","button_back");

			
    
}




static void UpdateLoadCB(void* pData)
{
//#ifndef PLATFORM_IOS
	//((FIGApp*)pData)->GetHandler()->UpdateOS();
//#endif
    
	((FIGApp*)pData)->UpdateLoadBar(1);
    
//#ifndef PLATFORM_IOS
	//((FIGApp*)pData)->GetHandler()->UpdateOS();
//#endif
    
	((FIGApp*)pData)->m_DebugLoadingCount++;
    
    if(g_pApp && g_pApp->GetHandler())
        g_pApp->GetHandler()->Tick(0);
}

//void	FIGApp::ChangeToUniCodeFont()
//{
//	if(m_pUnicodeFont)
//		FontManager::Instance().SetDefaultFont(m_pUnicodeFont);
//}

//void	FIGApp::ChangeToEnglishFont()
//{
//	if(m_pEnglishFont)
//		FontManager::Instance().SetDefaultFont(m_pEnglishFont);
//}
